import base64
import hashlib
import hmac
import time

import requests

from core.config import settings
from core.logger import log
from db.pydantic.request.sms import UpdatePhoneRequest, CreateGroupRequest, SendSmsPhoneRequest, SendSmsGroupRequest, \
    UpdateGroupRequest

def get_string_to_sign(method, endpoint, params):
    s = method + endpoint + "/?"
    query_str = "&".join("%s=%s" % (k, params[k]) for k in sorted(params))
    return s + query_str
def sign_str(key, s, method):
    hmac_str = hmac.new(key.encode("utf8"), s.encode("utf8"), method).digest()
    return base64.b64encode(hmac_str)
async def create_sms_group(create_req:CreateGroupRequest):
    url = "https://app.gotonesms.ink/api/v3/contacts"
    response = requests.post(url, headers=settings.SMS_API_Headers, json=create_req.model_dump())
    return response.json()


async def store_phone_to_group(group_id,store_req:UpdatePhoneRequest):
    url = f"https://app.gotonesms.ink/api/v3/contacts/{group_id}/store"
    response = requests.post(url, headers=settings.SMS_API_Headers, json=store_req.model_dump())
    return response.json()

async def search_phone_from_group(group_id,uid):
    if uid is None:
        url = f"https://app.gotonesms.ink/api/v3/contacts/{group_id}/all"
    else:
        url = f"https://app.gotonesms.ink/api/v3/contacts/{group_id}/search/{uid}"
    response = requests.post(url, headers=settings.SMS_API_Headers)
    return response.json()

async def search_group(group_id):
    url = f"https://app.gotonesms.ink/api/v3/contacts/{group_id}/show/"
    response = requests.post(url, headers=settings.SMS_API_Headers)
    return response.json()

async def update_phone_from_group(group_id,uid,update_req:UpdatePhoneRequest):
    url = f"https://app.gotonesms.ink/api/v3/contacts/{group_id}/update/{uid}"
    response = requests.post(url, headers=settings.SMS_API_Headers, json=update_req.model_dump())
    return response.json()
async def update_group(group_id,update_req:UpdateGroupRequest):
    url = f"https://app.gotonesms.ink/api/v3/contacts/{group_id}"
    response = requests.patch(url, headers=settings.SMS_API_Headers, json=update_req.model_dump())
    return response.json()
async def delete_phone_from_group(group_id,uid):
    url = f"https://app.gotonesms.ink/api/v3/contacts/{group_id}/delete/{uid}"
    response = requests.post(url, headers=settings.SMS_API_Headers)
    return response.json()
async def delete_group(group_id):
    url = f"https://app.gotonesms.ink/api/v3/contacts/{group_id}"
    response = requests.delete(url, headers=settings.SMS_API_Headers)
    return response.json()

async def get_all_group():
    url = "https://app.gotonesms.ink/api/v3/contacts/"
    response = requests.get(url, headers=settings.SMS_API_Headers)
    return response.json()

async def send_sms_by_phone(send_req:SendSmsPhoneRequest):
    url = "sms.tencentcloudapi.com"
    data = {
        "Nonce": "11886",
        "Timestamp": int(time.time()),
        "Region": "ap-beijing",
        "SecretId": settings.SMS_API_SECRET_ID,
        "Version": "2021-01-11",
        "Action": "SendSms",
        "SmsSdkAppId": "1401037222",
        "SignName": "合肥意数未来信息",
        "TemplateId": "2526701",
        "TemplateParamSet.0": send_req.message,
        "TemplateParamSet.1":5
    }
    # 添加电话号码列表
    for i, phone in enumerate(send_req.recipient):
        data[f"PhoneNumberSet.{i}"] = f"{phone}"
    s = get_string_to_sign("GET", url, data)
    data["Signature"] = sign_str(settings.SMS_API_SECRET_KEY, s, hashlib.sha1).decode('utf-8')
    log.info(f"签名: {data['Signature']}")
    log.info(f"PhoneNumberSet 类型: {type(send_req.recipient)}")
    response = requests.get("https://" + url, params=data)
    log.info(f"响应数据：{response.json()}")
    return response.json()

async def send_sms_by_group(send_req:SendSmsGroupRequest):
    url = "https://app.gotonesms.ink/api/v3/sms/campaign"
    response = requests.post(url, headers=settings.SMS_API_Headers, json=send_req.model_dump())
    return response.json()

async def get_sms(uid= None):
    if uid is None:
        url = "https://app.gotonesms.ink/api/v3/sms/"
    else:
        url = f"https://app.gotonesms.ink/api/v3/sms/{uid}"

    response = requests.get(url, headers=settings.SMS_API_Headers)
    return response.json()